import db from '../../uni_modules/vk-uview-ui/libs/function/debounce.js'
 
import {
	API_URL,
	IMG_URL
} from '../../env.js'
var loginnum = 0

function navTo(url, duration = 0, animationType = 'pop-in', animationDuration = 300) {
	if (!uni.getStorageSync('token')) {
		msg('请先登录')
		if (loginnum == 0) {
			loginnum++
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/login/login',
					success: () => {
						loginnum = 0
					}
				})
			}, 1500)
		}


		return
	}
	setTimeout(() => {
		uni.navigateTo({
			url: /^\//.test(url) ? url : `/${url}`,
			animationType,
			animationDuration,
			fail: () => {
				let param = getUrlParams(url)
				
				url = url.split('?')[0]
				uni.switchTab({
					url: /^\//.test(url) ? url : `/${url}`
				})
			}
		})
	}, duration)
}

function go(url, duration = 0, animationType = 'pop-in', animationDuration = 300) {

	setTimeout(() => {
		uni.navigateTo({
			url: /^\//.test(url) ? url : `/${url}`,
			animationType,
			animationDuration,
			fail: () => {
				let param = getUrlParams(url)
				
				url = url.split('?')[0]
				console.log(url)
				uni.switchTab({
					url: /^\//.test(url) ? url : `/${url}`
				})
			}
		})
	}, duration)
}

function goMore(url, duration = 0, animationType = 'pop-in', animationDuration = 300) {

	setTimeout(() => {
		uni.navigateTo({
			url: /^\//.test(url) ? url : `/${url}`,
			animationType,
			animationDuration,
			fail: () => {
				let param = getUrlParams(url)
				
				url = url.split('?')[0]

				uni.switchTab({
					url: /^\//.test(url) ? url : `/${url}`
				})
			}
		})
	}, duration)
}

function getUrlParams(search) {
	search = search || location.search;
	var paramsSplit = search.replace(/^[^\?]*\?/i, '').split('&');
	var params = {};

	if (Array.isArray(paramsSplit)) {
		paramsSplit.forEach(function(item) {
			const itemSplit = item.split('=');
			params[itemSplit[0]] = itemSplit[1];
		});
	}
	if (JSON.stringify(params) == '{}') {
		return null
	} else {
		return params
	}

}

function redirectTo(url, duration = 0, animationType = 'pop-in', animationDuration = 300) {

	setTimeout(() => {
		uni.redirectTo({
			url: /^\//.test(url) ? url : `/${url}`,
			animationType,
			animationDuration,
			fail: () => {
				uni.switchTab({
					url: /^\//.test(url) ? url : `/${url}`
				})
			}
		})
	}, duration)
}

function goBack(delta = 1, duration = 2000, animationType = 'pop-out', animationDuration = 300) {
	setTimeout(() => {
		uni.navigateBack({
			delta,
			animationType,
			animationDuration,
			fail: () => {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		})
	}, duration)
}

//获取前一页面对象
function beforePage() {
	let Pages = getCurrentPages()
	let beforePage = Pages[Pages.length - 2]
	return beforePage.$vm
}

function debounce(func, wait = 500, immediate = false) {
	db(func, wait, immediate)
}

function checklogin() {
	if (!uni.getStorageSync('token')) {
		msg('请先登录')
		if (loginnum == 0) {
			loginnum++
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/login/login',
					success: () => {
						loginnum = 0
					}
				})
			}, 1500)
		}


		return true
	} else {
		return false
	}

}

function wxpay(jsApiParameters) {
	return new Promise((resolve, reject) => {
		uni.requestPayment({
			provider: 'wxpay',
			appId: jsApiParameters.appId,
			timeStamp: jsApiParameters.timeStamp,
			nonceStr: jsApiParameters.nonceStr,
			package: jsApiParameters.package,
			signType: jsApiParameters.signType,
			paySign: jsApiParameters.paySign,
			success: function(res) {
				uni.hideLoading()
				resolve(true)

			},
			fail: function(res) {
				uni.hideLoading()
				uni.showModal({
					title: '支付失败',
					success: () => {

					}
				})

			},
			complete: function(res) {}
		})


	})
}

function showloading(msg = "") {
	uni.showLoading({
		title: msg,
		mask: true
	})

}

function upLoad(path) {

	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: API_URL + '/api/common/upload',
			filePath: path,
			header: {

				'token': uni.getStorageSync('token') || ''
			},

			name: 'file',
			success: uploadFileRes => {
				let file = uploadFileRes.data;
				file = JSON.parse(file);
				uni.hideLoading()
				if (file.code == 1) {
					resolve(file.data.url)
				} else if (file.code == 401) {
					uni.showModal({
						title: '温馨提示',
						content: '此时此刻需要您登录喔~',
						confirmText: "去登录",
						cancelText: "再逛会",
						success: function(res) {

							if (res.confirm) {
								uni.navigateTo({
									url: "/pages/login/login"
								});
							}
						}
					});
				} else {
					msg(file.msg)
				}




			},
			fail: () => {
				uni.hideLoading()
			}

		});


	})

}

function msg(msg) {
	// #ifdef APP-PLUS
	plus.nativeUI.toast(msg);
	// #endif
	// #ifndef APP-PLUS
	uni.showToast({
		title: msg,
		icon: 'none'
	})
	// #endif
}

function preImg(url, urls = null) {
	console.log(url)
	var a = url.slice(0, 4)
	if (a === 'http') {
		url = url
	} else if (url) {
		url = IMG_URL + url
	} else {
		return
	}
	if (!urls) {
		uni.previewImage({
			urls: [url],
			current: url
		})
	} else {
		let images = []
		urls.forEach(item => {
			let b = item.slice(0, 4)
			if (b === 'http') {

				images.push(item)
			} else {
				images.push(IMG_URL + item)

			}
		})

		uni.previewImage({
			urls: images,
			current: url
		})
	}


}

function makePhone(number) {
	if (!number) {
		return
	}
	uni.makePhoneCall({
		phoneNumber: number
	})

}

function openMap(lat, lng, name = '', address = '') {
	if (!lat) {
		return
	}
	uni.openLocation({
		latitude: Number(lat),
		longitude: Number(lng),
		scale: 18,
		name,
		address

	})

}

function copy(msg) {
	if (!msg) {
		return
	}
	// #ifdef H5
	var input = document.createElement("input");
	input.value = msg;
	document.body.appendChild(input);
	input.select();
	input.setSelectionRange(0, input.value.length), document.execCommand('Copy');
	document.body.removeChild(input);
	uni.showToast({
		title: '复制成功',
		icon: 'none',
		duration: 2000
	});
	// #endif
	// #ifndef H5
	uni.setClipboardData({
		data: msg,
		success: function() {
			uni.showToast({
				title: '复制成功',
				icon: 'none',
				duration: 2000
			});
			return true;
		},
		fail: function() {
			uni.showToast({
				title: '复制失败',
				icon: 'none',
				duration: 2000
			});
			return false;
		}
	});
	// #endif

}


function $timeago(dateTimeStamp) {
	dateTimeStamp = dateTimeStamp * 1000
	let result = ''
	var minute = 1000 * 60; //把分，时，天，周，半个月，一个月用毫秒表示
	var hour = minute * 60;
	var day = hour * 24;
	var week = day * 7;
	var halfamonth = day * 15;
	var month = day * 30;
	var now = new Date().getTime(); //获取当前时间毫秒
	console.log(now)
	var diffValue = now - dateTimeStamp; //时间差

	if (diffValue < 0) {
		return;
	}
	var minC = diffValue / minute; //计算时间差的分，时，天，周，月
	var hourC = diffValue / hour;
	var dayC = diffValue / day;
	var weekC = diffValue / week;
	var monthC = diffValue / month;
	if (monthC >= 1 && monthC <= 3) {
		result = " " + parseInt(monthC) + "月前"
	} else if (weekC >= 1 && weekC <= 3) {
		result = " " + parseInt(weekC) + "周前"
	} else if (dayC >= 1 && dayC <= 6) {
		result = " " + parseInt(dayC) + "天前"
	} else if (hourC >= 1 && hourC <= 23) {
		result = " " + parseInt(hourC) + "小时前"
	} else if (minC >= 1 && minC <= 59) {
		result = " " + parseInt(minC) + "分钟前"
	} else if (diffValue >= 0 && diffValue <= minute) {
		result = "刚刚"
	} else {
		var datetime = new Date();
		datetime.setTime(dateTimeStamp);
		var Nyear = datetime.getFullYear();
		var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
		var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
		var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
		var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
		var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
		result = Nyear + "-" + Nmonth + "-" + Ndate
	}
	return result;
}

function getDate() {
	var unixTimestamp = new Date();
	var year = unixTimestamp.getFullYear()

	var month = unixTimestamp.getMonth() + 1
	month > 9 ? '' : month = '0' + month
	var date = unixTimestamp.getDate()
	date > 9 ? '' : date = '0' + date

	let commonTime = year + "-" + month + "-" + date
	return commonTime
}

function saveImage(src = '') {

	// 向用户发起授权请求
	uni.authorize({
		scope: 'scope.writePhotosAlbum',
		success: () => {
			// 已授权
			downLoadImg(src);
		},
		fail: () => {
			// 拒绝授权，获取当前设置
			uni.getSetting({
				success: (result) => {
					if (!result.authSetting['scope.writePhotosAlbum']) {
						isAuth()
					}
				}
			});
		}
	})
}
/**
 * 下载资源，保存图片到系统相册
 */
function downLoadImg(src) {
	uni.showLoading({
		title: '加载中'
	});
	uni.downloadFile({
		url: src,
		success: (res) => {
			uni.hideLoading();
			if (res.statusCode === 200) {
				uni.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success: function() {
						uni.showToast({
							title: "保存成功",
							icon: "none"
						});
					},
					fail: function() {
						uni.showToast({
							title: "保存失败，请稍后重试",
							icon: "none"
						});
					}
				});
			}
		},
		fail: (err) => {
			uni.showToast({
				title: "失败啦",
				icon: "none"
			});
		}
	})
}
/*
 * 引导用户开启权限
 */
function isAuth() {
	uni.showModal({
		content: '由于您还没有允许保存图片到您相册里,无法进行保存,请点击确定允许授权',
		success: (res) => {
			if (res.confirm) {
				uni.openSetting({
					success: (result) => {
						console.log(result.authSetting);
					}
				});
			}
		}
	});
}

export default {
	go,
	goMore,
	navTo,
	redirectTo,
	goBack,
	beforePage,
	debounce,
	checklogin,
	wxpay,
	showloading,
	upLoad,
	msg,
	preImg,
	makePhone,
	openMap,
	copy,
	$timeago,
	saveImage,
	getDate
}